import { ref } from 'vue'
import { AiEditor } from '../lib/editor'

export const createAiEditor = (el, props, options,methods,$q) => {
  let toolbarKeys = [];
  let BasicToolbarKeys = [
    "undo", "redo", "brush", "eraser",
    "|", "heading", "font-family", "font-size",
    "|", "bold", "italic", "underline", "strike", "link", "code", "subscript", "superscript", "hr", "todo", "emoji",
    "|", "highlight", "font-color",
    "|", "align", "line-height",
    "|", "bullet-list", "ordered-list", "indent-decrease", "indent-increase", "break",
    "|", "image", "video", "attachment", "quote", "code-block", "table",
    "|", "find-replace", // "fullscreen",
    // "ai", "printer","source-code"
    // "|", "divider", "pdf-export", "word-export", "word-import", "chat"
  ];

  // 移动端且不可编辑时，只留一个【全屏】按钮
  if (options.isMobile.value && !options.editable) {
    toolbarKeys = ["fullscreen"]
  }
  //
  else {
    if (props.customizeToolbar == '1') {
      BasicToolbarKeys.forEach(item => {
        if (props.selectedToolbar.some(jj => jj.value == item)) {
          toolbarKeys.push(item)
        }
        if (item == "|") {
          if (toolbarKeys[toolbarKeys.length - 1] && toolbarKeys[toolbarKeys.length - 1] != "|") {
            toolbarKeys.push(item)
          }
        }
      })
    } else {
      if (props.isSimple) {
        toolbarKeys = ["bold", "italic", "underline", "strike", "image", "|", "align", "|", "fullscreen"]
      } else {
        toolbarKeys = _.cloneDeep(BasicToolbarKeys)
      }
    }

    if(props.enableComment){
      toolbarKeys.push({
        icon: `<svg t="1732240682228" class="icon" viewBox="0 0 1228 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1525" width="200" height="200"><path d="M76.8 61.44h776.192a51.2 51.2 0 0 1 28.2624 93.9008l-129.024 85.9136L653.5168 266.24l-443.8016 14.9504c12.3392 230.656 17.1008 347.648 14.1824 350.9248-4.7616 5.4272-9.472 11.1104-14.1824 16.9472-30.4128 37.888-59.4432 84.48-87.1424 139.6224A51.2 51.2 0 0 1 25.6 765.7472V112.64a51.2 51.2 0 0 1 51.2-51.2z" fill="#C9D1D9" opacity=".3" p-id="1526"></path><path d="M1152 35.84h-1075.2A76.8 76.8 0 0 0 0 112.64v819.2a76.8 76.8 0 0 0 76.8 76.8h1075.2A76.8 76.8 0 0 0 1228.8 931.84V112.64a76.8 76.8 0 0 0-76.8-76.8z m-1075.2 51.2h1075.2a25.6 25.6 0 0 1 25.6 25.6v819.2a25.6 25.6 0 0 1-25.6 25.6h-1075.2A25.6 25.6 0 0 1 51.2 931.84V112.64a25.6 25.6 0 0 1 25.6-25.6z" fill="#333333" p-id="1527"></path><path d="M860.16 266.24A61.44 61.44 0 0 1 921.6 327.68v285.8496a61.44 61.44 0 0 1-61.44 61.44H423.168L369.92 778.24l-53.3504-103.2704H266.24a61.44 61.44 0 0 1-61.44-61.44V327.68A61.44 61.44 0 0 1 266.24 266.24h593.92z" fill="#C9D1D9" opacity=".3" p-id="1528"></path><path d="M860.16 240.64H266.24a87.04 87.04 0 0 0-87.04 87.04v285.8496l0.3072 7.5264A87.04 87.04 0 0 0 266.24 700.5696l34.7136-0.0512 46.1824 89.4464 2.5088 3.9424a25.6 25.6 0 0 0 43.008-3.9424l46.1312-89.4464 421.376 0.0512a87.04 87.04 0 0 0 87.04-87.04V327.68a87.04 87.04 0 0 0-87.04-87.04z m-593.92 51.2h593.92a35.84 35.84 0 0 1 35.84 35.84v285.8496a35.84 35.84 0 0 1-35.84 35.84H423.168l-4.7104 0.4608a25.6 25.6 0 0 0-18.0224 13.4144l-30.5664 59.136-30.5664-59.136a25.6 25.6 0 0 0-22.7328-13.8752H266.24a35.84 35.84 0 0 1-35.84-35.84V327.68a35.84 35.84 0 0 1 35.84-35.84z" fill="#333333" p-id="1529"></path><path d="M640 368.64a25.6 25.6 0 0 1 4.608 50.7904L640 419.84h-307.2a25.6 25.6 0 0 1-4.608-50.7904L332.8 368.64h307.2z m-153.6 102.4a25.6 25.6 0 0 1 4.608 50.7904L486.4 522.24h-153.6a25.6 25.6 0 0 1-4.608-50.7904L332.8 471.04h153.6z" fill="#333333" p-id="1530"></path><path d="M819.2 624.64m-204.8 0a204.8 204.8 0 1 0 409.6 0 204.8 204.8 0 1 0-409.6 0Z" fill="#C9D1D9" p-id="1531"></path><path d="M819.2 394.24a230.4 230.4 0 1 0 0 460.8 230.4 230.4 0 0 0 0-460.8z m0 51.2a179.2 179.2 0 1 1 0 358.4 179.2 179.2 0 0 1 0-358.4z" fill="#333333" p-id="1532"></path><path d="M946.176 576.3584a25.6 25.6 0 0 1 10.9568 34.5088 90.624 90.624 0 0 1-16.5376 22.1696l18.3808 18.3808a25.6 25.6 0 0 1-32.6656 39.168l-3.584-2.9696-26.2144-26.2144a177.3568 177.3568 0 0 1-14.5408 5.2224l7.0656 26.4704a25.6 25.6 0 0 1-47.872 17.5616l-1.536-4.352-8.2432-30.7712a226.2016 226.2016 0 0 1-24.4736 0l-8.2432 30.7712a25.6 25.6 0 0 1-50.2272-8.704l0.768-4.5056 7.0656-26.5216a177.2544 177.2544 0 0 1-14.3872-5.1712l-26.1632 26.2144a25.6 25.6 0 0 1-39.168-32.6656l2.9184-3.584 18.3296-18.3296a90.624 90.624 0 0 1-16.5376-22.1696 25.6 25.6 0 0 1 42.9568-27.5456l2.5088 3.8912a44.8512 44.8512 0 0 0 11.5712 13.5168c17.7664 14.5408 47.7184 23.9104 80.896 23.9104s63.1296-9.3696 80.896-23.9104c3.584-2.9184 6.5024-5.9392 8.704-8.96l2.8672-4.5568a25.6 25.6 0 0 1 34.56-10.8544z" fill="#333333" p-id="1533"></path></svg>`,
        html:"",
        onClick: (event, editor) => {
            //点击事件
            methods.changeCommentStatus(editor)
        },
        tip: $q.lang.editorV2.showComment,
        active: true,
      })
    }

    // fullscreen【固定位置】
    toolbarKeys.push('fullscreen');
    // ai【固定位置】
    if (props.enableAi) {
      toolbarKeys.push('ai');
    }
  }

  return new AiEditor({
    element: el,
    placeholder: "",
    draggable: false,
    minHeight:props.minHeight,
    content: ``,
    toolbarSize: props.dense ? 'small' : 'medium',
    toolbarKeys: toolbarKeys,

    /** 针对【移动端】【切换全屏】时总是显示浮动提示且位置不对的问题，直接隐藏 */
    onFullscreen() {
      const tippyRoot = document.querySelector('[data-tippy-root]');
      if (tippyRoot) {
        tippyRoot.parentNode.removeChild(tippyRoot);
      }
    },

    onMentionQuery: async (query) => {
      let rows = [];
      let total;
      if (window.TFF && query) {
        const data = await TFF.common.ajax.getDataAsync({
          url: `${TFF.common.ajax.getServiceUrl(
            'SYS_CommonHelper_GetUserList',
          )}`,
          type: 'post',
          data: {
            filter: JSON.stringify({
              FieldName: 'RealName',
              FieldValue: query,
              FilterKey: {
                Data_FunctionID:
                  'DF686BBF-2387-4259-886B-249022156A8A',
                Enabled: 1,
                FilterByPeakOrgID: "fb247fb4-13d1-4c1b-acf8-27278b9bd0b1", //限定特来电内部用户
                NoDataAuth: 'true',
              },
              page: 1,
              rows: 10,
            }),
          },
        });
        rows = data.rows;
        total = data.total;
      }
      return rows.map(item=>{
        return {id:item.UserID,label:item.RealName}
      })

    },
    comment: {
      enable: options && options.commentEnable,
      enableWithEditDisable: true,
      onCommentActivated: (t) => {
        //当评论被激活时，鼠标选中了（或点击）了某段被标识的内容
      },
      queryAllComments: () => {
        const t = localStorage.getItem("all-comments"),
          e = t ? JSON.parse(t) : [],
          n = [];
        return (
          e.forEach((r) => {
            const i = localStorage.getItem(r);
            i && n.push(JSON.parse(i));
          }),
          n
        );
      },
      queryCommentsByIds: (t) => {
        const e = [];
        return (
          t &&
          t.forEach((n) => {
            const r = localStorage.getItem("comment-" + n);
            r && e.push(JSON.parse(r));
          }),
          e
        );
      },
      onCommentCreate: (t, e, n) => {
        console.log("onCommentCreate---->", t);
        const r = {
          id: t,
          pid: n,
          account: "张三",
          avatar: 'https://picsum.photos/30/30',
          mainColor: 'orange',
          createdAt: "2024-05-26 10:23:56",
          content: e,
        };
        localStorage.setItem("comment-" + t, JSON.stringify(r));
        const i = localStorage.getItem("all-comments"),
          s = i ? JSON.parse(i) : [];
        if (n) {
          const o = localStorage.getItem("comment-" + n);
          if (o) {
            const a = JSON.parse(o);
            a.children ? a.children.unshift(r) : (a.children = [r]),
              localStorage.setItem("comment-" + n, JSON.stringify(a));
          }
        } else s.push("comment-" + t);
        return (
          localStorage.setItem("all-comments", JSON.stringify(s)),
          new Promise((o) => {
            o(r);
          })
        );
      },
      onCommentDelete: (t) => (
        console.log("onCommentDelete---->", t),
        localStorage.removeItem("comment-" + t),
        !0
      ),
    },
    ...options,
    htmlPasteConfig: {
      removeEmptyParagraphs: false, // 已处理源码中的bug这里不设也ok了，不过还是保留空段比较合理
      pasteProcessor: (html) => {
        const parser = new DOMParser();
        const doc = parser.parseFromString(html, 'text/html');
        const fragment = document.createDocumentFragment();

        // 识别复制来源自钉钉文档的内容
        const cangjieArticle = doc.querySelector('article[data-clipboard-cangjie]');
        if (cangjieArticle) {
          const images = cangjieArticle.querySelectorAll('img');
          [].forEach.call(images, image => {
            const src = image.getAttribute('src') || '';
            const alt = image.getAttribute('alt') || '';
            if (src.includes('alidocs.oss')) {
              image.setAttribute(
                'alt',
                alt +
                  '阿里防盗链图片，暂无法展示，无须处理。后续系统自动替换为资源服务器地址！',
              );
            }
          });
          [].forEach.call(cangjieArticle.children, child => {
            fragment.appendChild((child).cloneNode(true));
          });
          const tempDiv = document.createElement('div');
          tempDiv.appendChild(fragment);
          return tempDiv.innerHTML;
        }

        return html;
      }
    },
  });
}
